package com.readfeed.app;

import java.text.ParseException;
import java.util.List;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.readfeed.app.adapter.CategoriesListAdapter;
import com.readfeed.app.data.FeedsAdapter;
import com.readfeed.app.fragment.AddCategoryDialogFragment;
import com.readfeed.app.fragment.DialogEventsListener;
import com.readfeed.app.fragment.ErrorDialogFragment;
import com.readfeed.app.fragment.ProgressDialogFragment;
import com.readfeed.app.model.Category;
import com.readfeed.app.utils.Utilities;

public class CategoriesListActivity extends Activity implements DialogEventsListener {

	public static final int MAX_CATEGORIES_COUNT = 10;
	public static final String CATEGORY_ID_EXTRA = "id";
	public static final String CATEGORY_TITLE_EXTRA = "title";
	private static final String CATEGORY_ADDED_MESSAGE = "Category added";
	private static final String CATEGORY_DELETED_MESSAGE = "Categoies deleted";
	
	private ListView mListView;
	private CategoriesListAdapter mListAdapter;
	private FeedsAdapter mFeedAdapter;	
	private FragmentManager mFragmentManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_categories_list);	
		
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		mFeedAdapter = new FeedsAdapter(this);
		mFeedAdapter.open();	
		
		mFragmentManager = getFragmentManager();
		mListView = (ListView)findViewById(R.id.categories_list_view);		
		this.configureListView();
		
		boolean isConnected = this.checkConnection();
		if (!isConnected) {
			Toast.makeText(this, "No network connection", Toast.LENGTH_LONG).show();
		}	  	
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		this.fillData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.categories_list, menu);
		return true;
	}	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.action_addcategory:
				if (mListAdapter.categoriesCount() == MAX_CATEGORIES_COUNT) {
					ErrorDialogFragment errorDialog = ErrorDialogFragment.newInstance(
							R.string.categories_max_count_error);
					errorDialog.show(mFragmentManager, Utilities.ERROR_DIALOG_TAG);
				} else {
					AddCategoryDialogFragment addDialog = AddCategoryDialogFragment.newInstance();						
					addDialog.show(mFragmentManager, Utilities.ADD_CATEGORY_DIALOG_TAG);					
				}
				
				break;		
			case R.id.categories_action_settings:
				Intent prefIntent = new Intent(CategoriesListActivity.this, PreferencesActivity.class);
				startActivity(prefIntent);
				
				break;
		}
		
		return true;
	}
	
	@Override
	protected void onDestroy() {	
		super.onDestroy();
	}
	
	private void configureListView(){
		mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
		mListView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

			private int selectedCount;
			
			@Override
			public boolean onActionItemClicked(ActionMode mode, MenuItem item) {	
				List<Category> categories = mListAdapter.getSelectedCategories();
				if (categories.size() != 0) {						
					switch (item.getItemId()) {                
	                case R.id.action_delete:
	                    selectedCount = 0;
	                    deleteCategories(categories);
	                    mListAdapter.removeSelectedCategories();
	                    mListAdapter.clearSelection();
	                    
	                    mode.finish();
					}
				} else {
					Toast.makeText(CategoriesListActivity.this, Utilities.NO_ITEMS_SELECTED_MESSAGE, Toast.LENGTH_SHORT).show();
				}
				
				return false;
			}										

			@Override
			public boolean onCreateActionMode(ActionMode mode, Menu menu) {
				selectedCount = 0;
				MenuInflater inflater = getMenuInflater();
				inflater.inflate(R.menu.context_menu, menu);
				return true;
			}

			@Override
			public void onDestroyActionMode(ActionMode mode) {
				mListAdapter.clearSelection();
				
			}

			@Override
			public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
				return false;			
			}

			@Override
			public void onItemCheckedStateChanged(ActionMode mode,
					int position, long id, boolean checked) {
				 if (checked) {
					 selectedCount++;
                     mListAdapter.setNewSelection(position, checked);                    
                 } else {
                	 selectedCount--;
                     mListAdapter.removeSelection(position);                 
                 }
				 
                 mode.setTitle(selectedCount + " items selected");
			}
		});
				
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Category clickedItem = mListAdapter.getCategoryByPosition(position);
				long databaseId = clickedItem.getId();
				String categoryTitle = clickedItem.getTitle();
				
				Intent intent = new Intent(CategoriesListActivity.this, ChannelsListActivity.class);
				intent.putExtra(CATEGORY_ID_EXTRA, databaseId);
				intent.putExtra(CATEGORY_TITLE_EXTRA, categoryTitle);
				
				startActivity(intent);
			}
		});
	}
	
	private void fillData(){
		GetCategoriesTask fillData = new GetCategoriesTask();
		fillData.execute();
	}
	
	private boolean checkConnection(){
		ConnectionDetector detector = new ConnectionDetector(this);
		return detector.isConnectingToInternet();
	}
	
	@SuppressWarnings("unchecked")
	private void deleteCategories(List<Category> list){
		DeleteCategyTask deleteTask = new DeleteCategyTask();
		deleteTask.execute(list);
	}
	
	@Override
	public void onDialogNegativeClick(DialogFragment dialog) {
		dialog.dismiss();	
	}
	
	@Override
	public void onDialogPositiveClick(DialogFragment dialog) {
		if (dialog instanceof AddCategoryDialogFragment) {				
			EditText view = (EditText)dialog.getDialog().findViewById(R.id.add_category_dialog);
			String title = view.getText().toString();
			
			boolean isValidTitle = Utilities.validateTitle(title);
			if (isValidTitle) {
				CreateCategoryTask task = new CreateCategoryTask();
				task.execute(title);
			} else {
				ErrorDialogFragment errorDialog = ErrorDialogFragment.newInstance(
						R.string.title_validation_error);
				errorDialog.show(mFragmentManager, Utilities.ERROR_DIALOG_TAG);
			}
		}	
	}
	
	private class GetCategoriesTask extends AsyncTask<Void, Void, List<Category>> {
		
		@Override
		protected List<Category> doInBackground(Void... params) {		
	    	List<Category> categoriesList = mFeedAdapter.getAllCategories();	    	
			return categoriesList;
		}
		
		@Override
		protected void onPostExecute(List<Category> result) {				
			mListAdapter = new CategoriesListAdapter(CategoriesListActivity.this, R.layout.category_row, result);
			mListView.setAdapter(mListAdapter);		
		}	
	}
	
	private class CreateCategoryTask extends AsyncTask<String, Void, Category>{
		
		@Override
		protected Category doInBackground(String... params) {
			Category category = new Category();
			category.setTitle(params[0]);					
			Category resultCategory = (Category) mFeedAdapter.createCategory(category);			
			return resultCategory;
		}
		
		@Override
		protected void onPostExecute(Category result) {
			mListAdapter.add(result);
			Toast.makeText(CategoriesListActivity.this, CATEGORY_ADDED_MESSAGE, Toast.LENGTH_LONG).show();
		}
	}
	
	private class DeleteCategyTask extends AsyncTask<List<Category>, Void, Void>{
		private Exception ex = null;
		
		@Override
		protected void onPreExecute() {		
			ProgressDialogFragment progressDialog = ProgressDialogFragment.newInstance(
					R.string.progress_dialog_loading);
			progressDialog.show(getFragmentManager(), Utilities.PROGRESS_DIALOG_TAG);
		}
		
		@Override
		protected Void doInBackground(List<Category>... categories) {
			
			List<Category> list = categories[0];
			try {
				mFeedAdapter.deleteCategories(list);
			} catch (ParseException e) {
				this.ex = e;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (this.ex != null) {
				((ProgressDialogFragment)mFragmentManager.findFragmentByTag(Utilities.PROGRESS_DIALOG_TAG)).dismiss();
				ErrorDialogFragment errorDialog = ErrorDialogFragment.newInstance(R.string.error_delete_categories);
				errorDialog.show(mFragmentManager, Utilities.ERROR_DIALOG_TAG);
			} else {
				((ProgressDialogFragment)mFragmentManager.findFragmentByTag(Utilities.PROGRESS_DIALOG_TAG)).dismiss();		
				Toast.makeText(CategoriesListActivity.this, CATEGORY_DELETED_MESSAGE, Toast.LENGTH_LONG).show();
			}			
		}
	}
}